package com.mmall.util;

import java.math.BigDecimal;

/**
 * BigDecimal的工具类，首先BigDecimal的构造器有好几种．
 * 但是只有String作为参数的构造器生成的BigDecimal才不会损失精度．
 * Created by qezhhnjy on 2017/10/1-20:48.
 */
public class BigDecimalUtil {

    private BigDecimalUtil() {
    }

    public static BigDecimal add(double v1, double v2) {
        BigDecimal var1 = new BigDecimal(Double.toString(v1));
        BigDecimal var2 = new BigDecimal(Double.toString(v2));
        return var1.add(var2);
    }

    public static BigDecimal substract(double v1, double v2) {
        BigDecimal var1 = new BigDecimal(Double.toString(v1));
        BigDecimal var2 = new BigDecimal(Double.toString(v2));
        return var1.subtract(var2);
    }

    public static BigDecimal multiply(double v1, double v2) {
        BigDecimal var1 = new BigDecimal(Double.toString(v1));
        BigDecimal var2 = new BigDecimal(Double.toString(v2));
        return var1.multiply(var2);
    }

    //除法由于会出现除不尽的情况，容易导致ArithmeticException.
    //所以方法中要设置保留小数位数scale,和舍入模式四舍五入。
    public static BigDecimal divide(double v1, double v2) {
        BigDecimal var1 = new BigDecimal(Double.toString(v1));
        BigDecimal var2 = new BigDecimal(Double.toString(v2));
        return var1.divide(var2, 2, BigDecimal.ROUND_HALF_UP);
    }

}
